import json
import requests
import sys

class ZabbixAPI():
    # 构造方法, 接收zabbix服务器地址、用户名、密码
    def __init__(self, ip, user, password):
        self.zabbix_url = "http://%s/zabbix/api_jsonrpc.php" % ip
        self.zabbix_user = user
        self.zabbix_password = password

    # 改写发送post请求的操作，返回字典格式的结果
    def send_post(self, data):
        head = { "Content-Type":"application/json" }
        try:
            res = requests.post(url=self.zabbix_url, data=json.dumps(data), headers=head)
        except Exception as e:
            print("发送请求失败，检查网络、数据格式是否正确")
            print(e)
            sys.exit()
        return json.loads(res.text)

    # 登录zabbix，获取令牌; __方法名称， 私有方法
    def __zabbix_login(self):
        data = {
           "jsonrpc": "2.0",
           "method": "user.login",
           "params": {
               "user": self.zabbix_user,
               "password": self.zabbix_password
           },
           "id": 1
        }
        res = self.send_post(data=data)
        token = res.get("result")
        return token

    # 获取模板Template OS Linux by Zabbix agent 的ID
    def get_template_id(self):
        token = self.__zabbix_login()
        data = {
           "jsonrpc": "2.0",
           "method": "template.get",
           "params": {
               "output": "extend",
               "filter": {
                   "host": [
                       "Template OS Linux by Zabbix agent",
                   ]
               }
           },
           "auth": token,
           "id": 1
        }
        res = self.send_post(data=data)
        template_id = res.get("result")[0].get("templateid")
        return template_id

    # 获取主机组ID
    def get_hostgroup_id(self, hostgroupname=None):
        token = self.__zabbix_login()
        # 获取所有的主机组
        all_hostgroup_data = {
           "jsonrpc": "2.0",
           "method": "hostgroup.get",
           "params": {
               "output": "extend",
           },
           "auth": token,
           "id": 1
        }
        res = self.send_post(data=all_hostgroup_data)
        # 规划字典，{"主机组名称":ID}
        all_hostgroup = {}
        for info in res.get("result"):
            all_hostgroup[info.get("name")] = info.get("groupid")
        # 判断主机组存在
        if hostgroupname in all_hostgroup.keys():
            hostgroup_id = all_hostgroup.get(hostgroupname)
            return hostgroup_id
        else:
            # 创建主机组
            create_hostgroup_data = {
                   "jsonrpc": "2.0",
                   "method": "hostgroup.create",
                   "params": {
                       "name": hostgroupname
                   },
                   "auth": token,
                   "id": 1
            }
            res = self.send_post(data=create_hostgroup_data)
            hostgroupid = res.get("result").get("groupids")[0]
            return hostgroupid

    # 添加监控主机
    def add_host(self, hostname, hostip, hostgroupname):
        token = self.__zabbix_login()
        hostgroupid = self.get_hostgroup_id(hostgroupname=hostgroupname)
        templateid = self.get_template_id()

        data = {
           "jsonrpc": "2.0",
           "method": "host.create",
           "params": {
               "host": hostname,
               "interfaces": [
                   {
                       "type": 1,
                       "main": 1,
                       "useip": 1,
                       "ip": hostip,
                       "dns": "",
                       "port": "10050"
                   }
               ],
               "groups": [
                   {
                       "groupid": hostgroupid
                   }
               ],
               "templates": [
                   {
                       "templateid": templateid
                   }
               ],
           },
           "auth": token,
           "id": 1
        }

        res = self.send_post(data=data)
        if "error" in res:
            print("主机【%s】添加监控失败" % hostip)
        else:
            print("主机【%s】添加监控成功" % hostip)





if __name__ == '__main__':
    p1 = ZabbixAPI(ip="192.168.140.10", user="Admin", password="zabbix")


    hostname = input("主机名称: ").strip()
    hostip = input("主机地址: ").strip()
    hostgroupname = input("主机组名称: ").strip()

    p1.add_host(hostname=hostname, hostip=hostip, hostgroupname=hostgroupname)